package com.zhanglijie.theory.produceandconsume;

import java.util.zip.CheckedOutputStream;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/13 0013 18:36
 */
public class MyQueue {
    private String[] buffer;
    private int count;
    private int head;
    private int tail;
    public MyQueue(int size){
        this.buffer = new String[size];
    }

    public synchronized void put(String str) throws InterruptedException {
        while(count>=buffer.length){
            wait();
            // put(str); 不可以递归 不然会塞相同的值进入到队列中  执行多次put
        }
        System.out.println(Thread.currentThread().getName()+"生产了===》"+str);
        buffer[tail] = str;
        // tail++;
        // if(tail == buffer.length){
        //     tail = 0;
        // }
       tail = ((tail+1)%buffer.length);
        count++;
        notifyAll();
    }

    public synchronized String get() throws InterruptedException {
        while(count<=0){
            wait();
          //  get(); 不可以改为if 递归 不然这个会执行多次get
        }
        if(count==0){
            wait();
        }
        String str = buffer[head];
        // head++;
        // if(head == buffer.length){
        //     head = 0;
        // }
          head = ((head+1)%buffer.length);//这个可以替换上面的多行注释
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName()+"消费了===》"+str);
        return str;
    }

    public synchronized void clear() {
        while(count != 0){
            String str = buffer[head];
            System.out.println(Thread.currentThread().getName()+"清理了====》"+str);
            head = (head+1)%buffer.length;
            count -- ;
        }
        head = 0;
        tail = 0;
        count = 0;
        notifyAll();
    }
}
